<?php

function postalcodes_save_postalcodes($parser, $data) {
  //Check if the coordinates should be preprocessed
  $p_info = postalcodes_get_parsers($parser);
  $process = isset($p_info['coordinate_processor']) && is_callable($p_info['coordinate_processor']);
  if ($process) {
    $processor = $p_info['coordinate_processor'];
  }
  
  foreach ($data as $pcode) {
    //Preprocess coordinates
    if($process) {
      list($coordinates, $center) = call_user_func($processor, $pcode[2]);
    }
    else {
      $coordinates = $pcode[2];
      $center = array(0,0);
    }
    
    //Add the postalcode to the database
    db_query("DELETE FROM {postalcodes} WHERE code_from=%d AND code_to=%d", array($pcode[0], $pcode[1]));
    db_query("INSERT INTO {postalcodes}(code_from, code_to, area, center) 
      VALUES (%d, %d, GeomFromText('%s'), GeomFromText('%s'))", 
      array(
        $pcode[0],
        $pcode[1],
        'POLYGON(('. $coordinates .'))', 
        'POINT('. $center[0] .' '. $center[1] .')'
      )
    );
  }
  
  return true;
}